import hashlib
import random

from django.http import JsonResponse


def MD5(val):
    md5 = hashlib.md5()
    md5.update(val.encode(encoding='utf-8'))
    return md5.hexdigest()


def is_empty_str(val):
    if type(val) != str:
        return True
    return val == ''


def str_len(val):
    typ = type(val)
    if typ != str:
        if typ == int or type == float:
            val = str(val)
        else:
            return 0
    return len(val)


def rand_str(length, typ=0):
    lower = 'abcdefghijklmnopqrstuvwxtz'
    upper = 'ABCDEFGHIJKLMNOPQRSTUVWXTZ'
    numbers = '0123456789'
    safe = '2346789ABCDEFGHJKLMNPRTUVWXTZ'
    charset = lower + upper + numbers
    if typ == 1:
        charset = lower + numbers
    elif typ == 2:
        charset = safe
    return ''.join(random.sample(charset, length))


def get_ip(request):
    if 'HTTP_X_FORWARDED_FOR' in request.META:
        ip = request.META['HTTP_X_FORWARDED_FOR']
    else:
        ip = request.META['REMOTE_ADDR']
    return ip


def success(data=None, **kwargs):
    resp = {
        'errcode': 0,
    }
    if data is not None:
        resp['data'] = data
    return JsonResponse({
        **resp,
        **kwargs
    })


def error(message='', **kwargs):
    resp = {
        "errcode": 10000,
        **kwargs
    }
    if message != '':
        resp['message'] = message
    return JsonResponse(resp)

